//全局语言对象
var oss = "http://foodievc.oss-ap-southeast-1.aliyuncs.com/" //国外
//var oss = "http://foodietest.oss-cn-beijing.aliyuncs.com/" //国内
var isAPP = navigator.userAgent.match(/Html5Plus/i)
var android_bak = true; //设置安卓返回键；
var root_a = "http://api-test.foodie.vc/"

var tab_and_fod = "http://foodietest.oss-cn-beijing.aliyuncs.com/" //测试使用
//var tab_and_fod = "http://foodievc.oss-ap-southeast-1.aliyuncs.com/" //正式使用

var api_root = root_a + "interface.php?ver=7&mo=s2&a=";
var api_img = root_a + "interface.php?ver=7&mo=s2&a=upload_Img"
var is_ajax_send = "0"; //锁定ajax
var isAPP = navigator.userAgent.match(/Html5Plus/i); //判断是否为app
var root ="123" //版本号
var lg = ""; //语言
var support = true; //刷新按钮开关
var con_img = "../images/yho.png" //默认图片
var phone_lg = ""; //手机默认语言
var global_lange = {} //全局语言对象
var phone_uuid = null; //手机唯一标识
var gpush_clientid = null; //手机唯一标识
var gpush_token = null; //手机唯一标识
var hour, minute, second; //时 分 秒
var timestamp_pe = null; //App从前台切换至后台所经过的时间
var timestamp_bg = null; //App从后台切换至前台所经过的时间
var set_p = {} //可拖拽长度
var uss = navigator.userAgent;
var newsaudio = new Audio(); //提示音乐
newsaudio.src = "../audio/ts.mp3";
var isAndroid = uss.indexOf('Android') > -1 || uss.indexOf('Adr') > -1; //android终端
var global_lange_config = {
	"zh": {
		name: "简体中文",
		val: "zh"
	},
	"en": {
		name: "English",
		val: "en"
	},
	"ms": {
		name: "Melayu",
		val: "ms"
	}
}
//取消浏览器的所有事件，使得active的样式在手机上正常生效
document.addEventListener('touchstart', function() {
	return false;
}, true);
// 禁止选择
document.oncontextmenu = function() {
	return false
};
//页面跳转
function jum(h) {
	if(isAPP) {
		var a = onNetChange()
		if(a == "error") {
			return
		} else {
			clicked(h);
		}
	} else {
		clicked(h);
	}

}
//全局返回上一页
function com_back() {
	back()
}
//Android返回
function And_back(page, a) {
	mui.back = function() {}
	if(navigator.userAgent.match(/Html5Plus/i)) {
		plus.key.removeEventListener("backbutton", plus_back1);
		plus.key.removeEventListener("backbutton", plus_back2);
		plus.key.removeEventListener("backbutton", plus_back3);
		plus.key.removeEventListener("backbutton", plus_back4);
		plus.key.removeEventListener("backbutton", plus_back6);
		if(page == "tab_sta") {
			plus.key.addEventListener("backbutton", plus_back2, false);

		} else if(page == "remove") {
			plus.key.addEventListener("backbutton", plus_back2, false);
		} else if(page == "index") {
			plus.key.addEventListener("backbutton", plus_back3, false);

		} else if(page == "con_order") {
			plus.key.addEventListener("backbutton", plus_back4, false);
		} else if(page == "myShop2") {
			plus.key.addEventListener("backbutton", plus_back6, false);
		} else if(page == "no") {
			plus.key.addEventListener("backbutton", function() {}, false);
		}
	}

}

function plus_back1() {
	var ws = plus.webview.currentWebview()
	plus.webview.close(ws.id)
}

function plus_back2() {
	back();
}
var backButtonPress2 = 0

function plus_back3() {
	if(backButtonPress2 >= 1) {
		plus.runtime.quit();
	} else {
		plus.nativeUI.toast(JSON.parse(getItem("Langues"))['1349']);
	}
	backButtonPress2++;
	setTimeout(function() {
		backButtonPress2 = 0;
	}, 1000);
	return false;
}

function plus_back4() {
	var ws = plus.webview.currentWebview()
	var ms = plus.webview.currentWebview().opener()
	//	var preUrl = plus.webview.getWebviewById(getItem("tableStatus.html"));
	ms.evalJS('refresh()')
	plus.webview.close(ws.id)
}

function plus_back6(a) {
	var ws = plus.webview.currentWebview()
	var preUrl = plus.webview.currentWebview().opener();
	preUrl.evalJS('refresh()');
	preUrl.evalJS('bank_btn(2)');
	plus.webview.close(ws.id)
}
var myDate = "";
//下拉刷新	
function down_load() {
	if(isAPP) {
		var ws = plus.webview.currentWebview();
		set_p = {
			support: true,
			style: 'circle', //必选，下拉刷新样式，目前支持原生5+ ‘circle’ 样式
			color: '#fd5749', //可选，默认“#2BD009” 下拉刷新控件颜色
			height: '50px', //可选,默认50px.下拉刷新控件的高度,
			range: '100px', //可选 默认100px,控件可下拉拖拽的范围
			offset: '-10px', //可选 默认0px,下拉刷新控件的起始位置
			auto: false, //可选,默认false.首次加载自动上拉刷新一次
			contentdown: {
				caption: "下拉可以刷新"
			},
			contentover: {
				caption: "释放立即刷新"
			},
			contentrefresh: {
				caption: "正在刷新..."
			}

		}
		ws.setPullToRefresh(set_p, function() {
			try {
				refresh(); //全局刷新
			} catch(e) {

			}
			//				back_index(1) //刷新方法
			ws.endPullToRefresh();
		});
	}

}
//检测网络环境
function onNetChange() {
	var w = plus.webview.currentWebview();
	var nt = plus.networkinfo.getCurrentType();
	//	switch(nt) {
	//		case plus.networkinfo.CONNECTION_ETHERNET:
	//			ee();
	//			break;
	//		case plus.networkinfo.CONNECTION_WIFI:
	//			ee();
	//			break;
	//		case plus.networkinfo.CONNECTION_CELL2G:
	//			ee();
	//			break;
	//		case plus.networkinfo.CONNECTION_CELL3G:
	//			ee();
	//			break;
	//		case plus.networkinfo.CONNECTION_CELL4G:
	//			ee();
	//			break;
	//		default:
	//			if(w.id != "/error404.html?3") {
	//				clicked("/error404.html")
	//			}
	//			return "error"
	//			break;
	//	}

	//	function ee() {
	//		var aa = plus.webview.getLaunchWebview();
	//		var bb = plus.webview.currentWebview();
	//		if(aa.id != bb.id) {
	//			var a = plus.webview.currentWebview().opener();
	//			a.evalJS('refresh()')
	//		}
	//		plus.webview.close("/error404.html?3");
	//
	//	}
}
$(function() {
	function plusReady1() {
		var a = getItem("lg") //读取本语言缓存
		//ISO去除延迟
		FastClick.attach(document.body);
		//当App从前台切换至后台
		//		document.addEventListener("resume", bg, false);
		And_back("remove")
		//设置默认语言
		if(getItem("root") != root) { //判断是否新版本 清除语言包缓存
			removeItem("lg");
			removeItem("Langues");
		}
		//加载本地语言包
		lang(a, function(h) {
			global_lange = h;
			fun1(); //每个页面的方法
			//			var qq = plus.webview.currentWebview()
			//			var ww = plus.webview.getLaunchWebview();
			if(isAPP) {
				onNetChange()
			}

		});
		$(document).on("click", "input", function() {
			$(this).focus();
		})
	}

	//判断是否app
	if(isAPP) {
		document.addEventListener('plusready', plusReady1, false);
	} else {
		plusReady1();

	}

})

//退出清除缓存
function global_signout(a) {
	removeItem("login_sta"); //登录状态
	removeItem("my_msg"); //个人信息缓存
	removeItem("encode"); //头信息
	mui.alert(a,function(){
		plus.runtime.restart()//重启app
	},"div")
//	clicked("../login/login.html") //全局
}
//ajax加载语言包
function lang(v, call, type) {
	if(!v) {
		var lg = navigator.language.toLowerCase().substr(0, 2)
		var langarr = ["zh", "en", "ms"]
		if(langarr.indexOf(lg) == -1) lg = "en"
		setItem("lg", lg);
		v = lg;
	}
	var l = getItem("Langues"); //json
	var lang = getItem("lg"); //zh en ms
	lg = lang;
	if(l && v == lang) { //vue回调
		call(JSON.parse(l));
	} else { //切换与初始化语言
		$.ajax({
			type: "get",
			dataType: "json",
			url: "../language/" + v + ".json",
			success: function(h) {
				setItem("Langues", JSON.stringify(h));
				setItem("lg", v);
				call(h);
			},
			error: function(e) {
				console.log("语言包加载错误");
				debugger
			}
		});
	}
	//	if(type == "1") {  //更新语言包时使用
	//		$.ajax({
	//			type: "get",
	//			dataType: "json",
	//			url: "../language/" + v + ".json",
	//			success: function(h) {
	//				setItem("Langues", JSON.stringify(h));
	//				setItem("lg", v);
	//				call(h);
	//			},
	//			error: function(e) {
	//				console.log("语言包加载错误");
	//				debugger
	//			}
	//		});
	//	}
}

//缓存json数据
function global_json1(url, call) {
	var ss = JSON.parse(getItem("my_msg"))
	var aa = ""
	if(isAPP) {
		aa = tab_and_fod + url + ss.shop_id + "_" + getItem("lg") + ".json"
	} else {
		if(url == "/shop_goods/") {
			aa = "../language/foods.json"
		} else {
			aa = "../language/table.json"
		}
	}
	if(ss.waiter_status == 3) {
		call(ss.waiter_status)
		return
	}
	$.ajax({
		type: "get",
		dataType: "json",
		url: aa,
		success: function(h) {
			call(h)
		},
		error: function() {
			alert("接口错误", "提示");
		}
	});
}
//统计点击次数
function click_ajax(data, call) {
	$.ajax({
		"type": "post",
		"dataType": "String",
		//		"timeout": 20000,
		"data": data,
		headers: {
			"WAITER-ENCODE": getItem("encode")
		},
		"url": "http://api-test.foodie.vc/index.php?s=/Home/Adv/put_click",
		"success": function(h) {
			//				if(h.status==2 || h.status==3 && type==2){1成功 0失败 2登录超时 3帐号锁定
			call(h);
		},
		"error": function(e) {
			//			alert("接口错误!", "提示");
			//			alert(JSON.stringify(e))
		}
	})

}
//请求数据ajax
function common_ajax(type, data, href, call) { //type:1获取数据 2:获取json文件 请求memberid 与shopid  data:传入数据      call:成功回调  href:接口名称 4:获取图片
	data.uuid = getItem("uuid")
	if(is_ajax_send == "1") { //判断ajax是否处于锁定状态 0:未锁定 1:已锁定
		console.log("重复调用接口")
		return;
	}
	var wss1 = null;
	is_ajax_send = "1";
	var url, headers = {};
	timejson = setInterval(function() {
		clearInterval(timejson);
		if(isAPP) {
			wss1 = plus.nativeUI.showWaiting("loading...", {
				loading: {
					display: "inline"
				}
			});
		}
	}, 700);
	lg = getItem("lg");
	if(type == 1) { //登录注册忘记密码
		url = api_root + href + '&l=' + lg;
	}
	console.log("data",data)
	if(type == 1) {
		$.ajax({
			"type": "post",
			"dataType": "json",
			//			"timeout": 20000,
			"data": data,
			headers: {
				"WAITER-ENCODE": getItem("encode")
			},
			"url": url,
			"success": function(h) {
				//				if(h.status==2 || h.status==3 && type==2){1成功 0失败 2登录超时 3帐号锁定
				success(h);
			},
			"error": function(e) {
				console.log("ee",data)
				errors(e);
			}
		})
	}
	if(type == 2) {
		$.ajax({
			"type": "get",
			"dataType": "json",
			"timeout": 20000,
			"data": data,
			"url": 'http://foodietest.oss-cn-beijing.aliyuncs.com//shop_goods/8_zh.json',
			"success": function(h) {
				//				if(h.status==2 || h.status==3 && type==2){1成功 0失败 2登录超时 3帐号锁定
				success(h);
			},
			"error": function(e) {
				errors(e);
			}
		})
	}
	if(type == 4) {
		//上传图片用
		$.ajax({
			type: "post",
			dataType: "json",
			timeout: 15000,
			url: api_img,
			headers: {
				"WAITER-ENCODE": getItem("encode")
			},
			data: data,
			contentType: false,
			processData: false,
			success: function(h) {
				success(h);
			},
			error: function(e) {
				console.log(e);
			}
		});
	}
	//ajax成功后回调
	function success(h) {
		is_ajax_send = 0;
		clearInterval(timejson);
		if(wss1 != null) {
			wss1.close();
		}
		//判断是否登录异常
		if(h.status == 2 || h.status == 3) { //1成功 0失败 2登录超时 3帐号锁定
			global_signout(h.msg); //全局退出
		} else {
			call(h);
		}

	}

	//ajax错误回调
	function errors(e) {
		is_ajax_send = 0;
		if(wss1 != null) {
			wss1.close();
		}
		clearInterval(timejson);
	}
}
//验证是否有权限
function verify(num, call) {
	var str  ="<div id='table_open_mask' class='mask' style='z-index: 99;'></div><div id='verification' class='jurisdiction fiex'><div class='jurisdiction_son fiex1'><div class='fiex f-20 center mag-b-20'>"+ global_lange["1496"]+"</div><div class='fiex mag-b-20'><div class='f-18 mag-r-10'>"+global_lange["1497"]+"</div><div class='fiex1'><input id='account' placeholder="+global_lange['1152']+" type='text' /></div></div><div class='fiex mag-b-20'><div class='f-18 mag-r-10'>"+ global_lange["1498"]+"</div><div class='fiex1'><input id='password' placeholder="+global_lange['1004']+" type='password' /></div></div><div class='fiex'><div class='fiex1 center'><div id='verification_sub' class='btn btn_c'>"+global_lange["1190"]+"</div></div><div class='fiex1 center'><div id='verification_cancle' style='background: #aaa;' class='btn btn_c'>"+global_lange["1049"]+"</div></div></div></div></div>"
	function dele_str(){
		$("#table_open_mask").remove()
		$("#verification").remove()
	}
	var m = JSON.parse(getItem("shop_table_cookbook")).rule_list;
	if(m==null){
		call(1)
		return
	}
	var account = "";
	var password = "";
	var s = false
	$.each(m, function(k, v) {
		if(num == v) {
			s = true
			return false
		}
	});
	if(s) {
		call(1)
	} else {
		popups();
	}
	//验证弹出层
	function popups() {
		$("#app").append(str)
		document.getElementById("table_open_mask").addEventListener('touchmove', function(e) {
			e.preventDefault()
		}, false)
		document.getElementById("verification").addEventListener('touchmove', function(e) {
			e.preventDefault()
		}, false)
		
		$('#verification_sub').unbind("click");
		$('#verification_cancle').unbind("click");
		$("#verification_sub").on("click", function() {
			var a = $("#account").val()
			var p = $("#password").val()
			setajx(a, p)
		})
		$("#verification_cancle").on("click", function() {
			dele_str()
		})
	}

	function setajx(a, p) {
		common_ajax("1", {
			"username": a,
			"password": p,
			"rule_id": num
		}, "get_cashier_validation", function(e) {
			var star = e.status;
			if(star == 1) {
				$("#table_open_mask").addClass('hide')
				$("#verification").addClass('hide')
				call(1);
				dele_str();
			} else {
				call(0);
			}
		})
	}
}